<!--
* description: 新增编辑-价格策略维护
-->
<template>
  <section class="editCarBrand">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      width="70%"
      @close="sendCode"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />
      <div class="filter-container filter-params">
        <el-row :gutter="26">
          <component
            :is="comp.component"
            v-for="comp in tableComponents.filter((o) => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :o-fields="comp.oFields"
            :options="comp.options"
            :custom-obj="comp.customObj"
            :is-require="comp.isRequire"
            :is-mul="comp.isMul"
            :span="comp.span || 8"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :data-to-object="comp.dataToObj"
            :date-options-type="comp.dateOptionsType"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
          />
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          @click="comp.clickEvent"
        >{{ comp.text }}</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from '@/components/wms/mixins/formMixins'
import api from '@/api/pa/apiBaseData'
export default {
  components: {
    dialogHeader: () => import('@/components/dialogHeader') // 弹窗标题
  },
  // 组件混入对象
  mixins: [formMixins],
  props: {
    existingRepairType: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.save(),
          text: '保存' // "保存"
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          clickEvent: () => this.reset(),
          text: '重置' // "重置"
        }
      ],
      // 动态组件-查询条件
      tableComponents: [
        {
          compKey: 'edit_compKey1',
          labelName: '维修类型：', // 维修类型：
          codeField: 'partRepairType',
          textField: 'partRepairTypeName',
          // customObj: {
          //   api: api.queryPartRepairs
          // },
          options: [
            {
              'lookupValueCode': '1',
              'lookupValueName': '保养件',
              disabled: false
            },
            {
              'lookupValueCode': '8',
              'lookupValueName': '套餐类备件',
              disabled: false
            },
            {
              'lookupValueCode': '7',
              'lookupValueName': '工具',
              disabled: false
            },
            {
              'lookupValueCode': '2',
              'lookupValueName': '易损件',
              disabled: false
            },
            {
              'lookupValueCode': '9',
              'lookupValueName': '服务合同',
              disabled: false
            },
            {
              'lookupValueCode': '6',
              'lookupValueName': '生活精品',
              disabled: false
            },
            {
              'lookupValueCode': '3',
              'lookupValueName': '碰撞件',
              disabled: false
            },
            {
              'lookupValueCode': '5',
              'lookupValueName': '精品附件',
              disabled: false
            },
            {
              'lookupValueCode': '4',
              'lookupValueName': '维修件',
              disabled: false
            }
          ],
          disabled: false,
          component: () => import('@/components/org/commonSelect'),
          isRequire: true,
          span: 12,
          isMust: true,
          isMul: false
        },

        {
          compKey: 'edit_compKey2',
          labelName: '备件名称码：', // "备件名称码："
          codeField: 'partNameValue',
          isRequire: true,
          disabled: false,
          validrule: {
            isformat: '/^[a-zA-Z\\d]+/',
            resectMessage: {
              isformat: '请输入正确备件名称码'
            }
          },
          component: () => import('@/components/org/commonInput'),
          isMust: true,
          span: 12
        },
        {
          compKey: 'edit_compKey3',
          labelName: '总部利润率(%)：',
          codeField: 'oemProfitMarginL',
          span: 6,
          validrule: {
            // 保留一到两位小数
            isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
            resectMessage: {
              isformat: '请输入正确的利润率!'
            }
          },
          component: () => import('@/components/org/commonInput'),
          isRequire: true,
          isMust: true
        },
        {
          compKey: 'edit_compKey4',
          labelName: '~(%)',
          codeField: 'oemProfitMarginH',
          span: 6,
          validrule: {
            // 保留一到两位小数
            isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
            resectMessage: {
              isformat: '请输入正确的利润率!'
            }
          },
          component: () => import('@/components/org/commonInput'),
          isRequire: true,
          isMul: false,
          isMust: true
        },
        {
          compKey: 'edit_compKey5',
          labelName: '总部最低利润率（%）：', // "总部最低利润率"
          span: 12,
          validrule: {
            // 保留一到两位小数
            isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
            resectMessage: {
              isformat: '请输入正确的利润率!'
            }
          },
          codeField: 'oemProfitMarginMin',
          component: () => import('@/components/wms/commonInput'),
          type: 'inputText',
          isRequire: true,
          isMust: true
        },

        {
          compKey: 'edit_compKey7',
          labelName: '网点利润率(%)：',
          codeField: 'dlrProfitMarginL',
          validrule: {
            // 保留一到两位小数
            isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
            resectMessage: {
              isformat: '请输入正确的利润率!'
            }
          },
          span: 6,
          component: () => import('@/components/org/commonInput'),
          isMust: true,
          isRequire: true
        },
        {
          compKey: 'edit_compKey8',
          labelName: '~(%)',
          codeField: 'dlrProfitMarginH',
          span: 6,
          validrule: {
            // 保留一到两位小数
            isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
            resectMessage: {
              isformat: '请输入正确的利润率!'
            }
          },
          component: () => import('@/components/org/commonInput'),
          isMust: true,
          isRequire: true
        },
        {
          compKey: 'edit_compKey9',
          labelName: '网点最低利润率：', // '网点最低利润率：',
          span: 12,
          validrule: {
            // 保留一到两位小数
            isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
            resectMessage: {
              isformat: '请输入正确的利润率!'
            }
          },
          codeField: 'dlrProfitMarginMin',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          isRequire: true
        },
        // {
        //   compKey: 'edit_compKey6',
        //   labelName: '紧急订单浮动率（%）：', // "紧急订单浮动率："
        //   validrule: {
        //     // 保留一到两位小数
        //     isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
        //     resectMessage: {
        //       isformat: '请输入正确的利润率!'
        //     }
        //   },
        //   span: 12,
        //   codeField: 'urgentOrderFloatingRate',
        //   component: () => import('@/components/org/commonInput'),
        //   isMust: true,
        //   isRequire: true
        // },
        {
          compKey: 'edit_compKey10',
          labelName: '状态：',
          span: 12,
          codeField: 'isEnable',
          component: () => import('@/components/org/LookupValue'),
          oFields: 'value,text',
          options: [
            { value: '1', text: '启用' },
            { value: '0', text: '停用' }
          ],
          type: 'dropdownList',
          isRequire: true,
          isMust: true
        },
      ],
      // 标题
      textMap: {
        edit: '价格策略信息编辑',
        add: '价格策略信息新增'
      },
      // 表单数据（无需赋值，由混入对象赋值）
      formField: {
        partRepairType: '',
        partNameValue: '',
        oemProfitMargin: '',
        oemProfitMarginMin: '',
        oemProfitMarginL: '',
        oemProfitMarginH: '',
        // urgentOrderFloatingRate: '',
        dlrProfitMargin: '',
        dlrProfitMarginMin: '',
        dlrProfitMarginL: '',
        dlrProfitMarginH: '',
        isEnable: '',
        updateControlId: '',
        priceStrategyId: ''
      }
    }
  },
  watch: {
    popupsVisible(val) {
      if (val) {
        if (
          this.formField.pageId !== '' &&
          this.$route.query.pageId !== undefined &&
          this.$route.query.pageId !== this.formField.pageId
        ) {
          this.formField.pageId = this.$route.query.pageId
          this.formField.pageName = this.$route.query.pageName
        }
        this.formField.langLabelName = this.formField.label
        this.backFormField = JSON.parse(JSON.stringify(this.formField))
      }
    }
  },
  mounted() {
    // this.tableComponents.find(comp => comp.codeField === 'partRepairType').options.forEach(opt => {
    //   if (this.existingRepairType.includes(opt['lookupValueCode'])) {
    //     opt.disabled = true
    //   }
    // })
  },
  methods: {
    onCreated() {
      if (this.popupsState == 'edit') {
        //  Object.keys(that.formField).forEach((key)=>{
        //     that.formField[key]=RegExp(/%/).test(that.formField[key])?parseFloat(that.formField[key]):that.formField[key]
        //   })
        this.tableComponents[0].disabled = true
        // this.tableComponents[1].disabled = true
        this.formField.oemProfitMarginL = this.formField.oemProfitMargin
          .split('~')[0]
          .replace(/%/g, '')
        this.formField.oemProfitMarginH = this.formField.oemProfitMargin
          .split('~')[1]
          .replace(/%/g, '')
        this.formField.dlrProfitMarginL = this.formField.dlrProfitMargin
          .split('~')[0]
          .replace(/%/g, '')
        this.formField.dlrProfitMarginH = this.formField.dlrProfitMargin
          .split('~')[1]
          .replace(/%/g, '')
        this.formField.oemProfitMarginMin = parseFloat(
          this.formField.oemProfitMarginMin
        )
        this.formField.urgentOrderFloatingRate = parseFloat(
          this.formField.urgentOrderFloatingRate
        )
        this.formField.dlrProfitMarginMin = parseFloat(
          this.formField.dlrProfitMarginMin
        )
      }
    },
    // 新增/编辑保存按钮
    save() {
      this.$utils.validataMoth(this, 'validpopup')
      if (this.valid) {
        if (this.popupsState == 'edit') {
          this.editSave()
        } else {
          this.addSave()
        }
      }
    },
    // 修改
    editSave() {
      const that = this
      // Object.keys(that.formField).forEach((key) => {
      //   that.formField[key] = RegExp(/%/).test(that.formField[key])
      //     ? parseFloat(that.formField[key])
      //     : that.formField[key];
      // });
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: api.updatePriceStrategy,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: this.$t('sys.tips.esTip5') /* 保存成功*/,
            type: 'success',
            duration: 1000
          })
          this.curPopupsVisible = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({
            message: '保存失败:' + response.msg,
            type: 'warn',
            uration: 1000
          })
        }
      })
    },
    // 修改
    addSave() {
      const that = this
      // Object.keys(that.formField).forEach((key) => {
      //   that.formField[key] = RegExp(/%/).test(that.formField[key])
      //     ? parseFloat(that.formField[key])
      //     : that.formField[key];
      // });
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: api.addPriceStrategy,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: this.$t('sys.tips.esTip5') /* 保存成功*/,
            type: 'success',
            duration: 1000
          })
          this.curPopupsVisible = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message(response.msg || '保存失败!')
        }
      })
    }
  }
}
</script>
<style type="text/css" scoped>
.filter-params .el-col label .curName {
  width: 150px;
}
</style>
